package preprocess;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

/**
 * XML数据发送类
 * 
 * @author yan
 * @version 0.1
 */
public class XmlGenerate extends Thread
{
    private String            path   = "";
    private PipedOutputStream sender = new PipedOutputStream();

    public XmlGenerate(String getPath)
    {
        path = getPath;
    }

    public PipedOutputStream getOutputStream()
    {
        return sender;
    }

    public File[] getAllXMLFiles(File path)
    {
        Set<File> set = new HashSet<File>();
        listXMLFiles(path, set);
        return set.toArray(new File[0]);
    }

    private void listXMLFiles(File path, Set<File> set)
    {
        for (File f : path.listFiles())
        {
            if (f.isDirectory())
                listXMLFiles(f, set);
            else if (f.getName().toLowerCase().endsWith(".xml"))
                set.add(f);
        }
    }

    public void run()
    {
        int fileLength = 0;
        byte[] byteStr = null;
        FileInputStream fileStr = null;
        if (path.equals(""))
            System.out.println("路径为空");
        else
        {
            File rootDir = new File(path);
            File[] fileList = getAllXMLFiles(rootDir);
            HashSet<File> oldSet = new HashSet<File>();
            do
            {
                for (int i = 0; i < fileList.length; i++)
                {
                    /* 添加一发现的文件到oldSet */
                    oldSet.add(fileList[i]);

                    try
                    {
                        XmlTransfer.critical.getWriteLock();
                        fileStr = new FileInputStream(fileList[i]);
                        fileLength = fileStr.available();
                        XmlTransfer.length = fileLength;
                        byteStr = new byte[fileLength];
                        fileStr.read(byteStr, 0, fileLength);
                        for (int out = fileLength; out > 0;)
                        {
                            XmlTransfer.critical.getWriteLock();
                            // if (!XmlTransfer.isFull)
                            // {
                            if (out >= XmlTransfer.pipeSize)
                                sender.write(byteStr, fileLength - out,
                                        XmlTransfer.pipeSize);
                            else
                                sender.write(byteStr, fileLength - out, out);
                            if (out == fileLength)
                            {
                                XmlTransfer.isNew = true;
                                XmlTransfer.xmlName1 = fileList[i].getName()
                                        .toString();
                                if (i > 0)
                                    XmlTransfer.xmlName2 = fileList[i - 1]
                                            .getName().toString();
                            }
                            else
                            {
                                XmlTransfer.isNew = false;
                            }
                            out = out - XmlTransfer.pipeSize;
                            XmlTransfer.critical.releaseWriteLock();
                        }

                        /* 看是否需要继续发送 */
                        while (XmlTransfer.isGoOn == false)
                        {
                            try
                            {
                                Thread.sleep(XmlTransfer.timeInterval);
                            }
                            catch (InterruptedException e)
                            {
                                e.printStackTrace();
                            }
                        }

                        // 休眠指定时间以后再发送下一篇
                        try
                        {
                            sleep(XmlTransfer.timeInterval);
                        }
                        catch (Exception e)
                        {}
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }

                /* 监听文件夹，加入新到的文件 */
                if (XmlTransfer.listenDir != ""
                        && XmlTransfer.listenDir != null)
                {
                    HashSet<File> newSet = new HashSet<File>();
                    DirListener listener = new DirListener(
                            XmlTransfer.listenDir, oldSet, newSet);
                    listener.start();
                    try
                    {
                        listener.join();
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }

                    fileList = newSet.toArray(new File[0]);
                    try
                    {
                        sleep(XmlTransfer.timeInterval);
                    }
                    catch (Exception e)
                    {}
                }
                else
                {
                    fileList = new File[0];
                    try
                    {
                        sleep(XmlTransfer.timeInterval);
                    }
                    catch (Exception e)
                    {}
                }
            }
            while (true);
        }
    }
}

class DirListener extends Thread
{
    // 这里需要指定需要监控的文件夹路径
    private String    listenerFile = null;

    private Set<File> oldSet       = null;
    private Set<File> newSet       = null;

    public DirListener(String dirPath, HashSet<File> initOldSet,
            HashSet<File> initNewSet)
    {
        this.listenerFile = dirPath;
        this.oldSet = initOldSet;
        this.newSet = initNewSet;
    }

    public File[] getAllXMLFiles(File path)
    {
        Set<File> set = new HashSet<File>();
        listXMLFiles(path, set);
        return set.toArray(new File[0]);
    }

    private void listXMLFiles(File path, Set<File> set)
    {
        for (File f : path.listFiles())
        {
            if (f.isDirectory())
                listXMLFiles(f, set);
            else if (f.getName().toLowerCase().endsWith(".xml"))
                set.add(f);
        }
    }

    public void run()
    {
        try
        {
            Set<File> newSet = this.newSet;
            File dir = new File(listenerFile);
            if (dir.isDirectory())
            {
                // TODO:这里需要文件抓取部分的同步访问
                File[] files = this.getAllXMLFiles(dir);
                for (File file : files)
                {
                    if (!this.oldSet.contains(file))
                    {
                        newSet.add(file);
                    }
                }
            }
            else
            {
                System.err.println("The listener file path" + listenerFile
                        + " is not a directory");
            }

            Thread.sleep(10 * 1000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
